# coding: utf-8

import tempfile
from subprocess import Popen, PIPE

from .base import BaseWorker


class NonRecoverableError(Exception):
    pass


def get_inventory_path(target, port):
    _, path_to_file = tempfile.mkstemp()

    with open(path_to_file, 'w') as f:
        f.write('{} ansible_ssh_port={}\n'.format(target, port))

    return path_to_file


def run_command(command):

    try:
        run = Popen(command, stdout=PIPE, stderr=PIPE)
    except Exception as e:
        output = 'Popen Exception: {} msg: {}'.format(e.__class__, e)
        status = 'F'
        return status, output

    try:
        output, status = run.communicate()
        print output, status
    except Exception as e:
        output = 'Communicate Exception: {} msg: {}'.format(e.__class__, e)

    if run.returncode != 0:
        status = 'F'
    else:
        status = 'S'
    return status, output


class AnsibleWorker(BaseWorker):

    def _execute(self):
        pass
